// draggable.ts  
import type{ Directive, DirectiveBinding } from 'vue';  
  
const DraggableDirective: Directive = {  
  mounted(el: HTMLElement, binding: DirectiveBinding) {  
    // 初始化拖拽相关变量  
     const parentElement = el.parentElement;  
    let offsetX = 0;  
    let offsetY = 0;  
    let initialX = 0;  
    let initialY = 0;  
      
    // 假设 binding.value 是一个对象，包含了区域的边界信息  
    const { minX, minY, maxX, maxY } = binding.value || { minX: 0, minY: 0, maxX: Infinity, maxY: Infinity };  
      
    el.addEventListener('mousedown', (event) => {  
      offsetX = event.clientX - el.getBoundingClientRect().left;  
      offsetY = event.clientY - el.getBoundingClientRect().top;  
      initialX = el.offsetLeft;  
      initialY = el.offsetTop;  
        
      document.addEventListener('mousemove', onMouseMove);  
      document.addEventListener('mouseup', onMouseUp);  
    });  
  
    function onMouseMove(event: MouseEvent) {  
      const newX = event.clientX - offsetX;  
      const newY = event.clientY - offsetY;  
        
      // 计算新的位置，并限制在指定区域内  
      const newLeft = Math.max(0, Math.min(newX - initialX, parentElement.offsetWidth - el.offsetWidth));  
      const newTop = Math.max(0, Math.min(newY - initialY, parentElement.offsetHeight - el.offsetHeight));  
        
     
      el.style.left = `${newLeft}px`;  
      el.style.top = `${newTop}px`;   
    }  
  
    function onMouseUp() {  
      document.removeEventListener('mousemove', onMouseMove);  
      document.removeEventListener('mouseup', onMouseUp);  
    }  
  },  
  unmounted() {  
    // document.removeEventListener('mousemove', onMouseMove);  
    // document.removeEventListener('mouseup', onMouseUp);  
  }  
};  
  
export default DraggableDirective;